//
//  JobsInputSearchView.swift
//  GreenDeal
//
//  Created by yly on 2024/5/20.
//

import UIKit
import RxSwift
import RxCocoa
import DaisyNet

class JobsInputSearchView: GreenNaviBarView {
    
    fileprivate lazy var disposeBag = DisposeBag()
    var editingChangedClosure: ((_ jobStr :String ,_ addressStr :String , _ addressModel :PhysicalAddressViewModel?)->Void)?
    
    // text
    let searchTextfield = DIYTextField()

    // address
    var addressStr: String = ""
    var addressModel: PhysicalAddressViewModel?
    
    let addressTextfield = DIYTextField()
    
//    let viewTabBg = UIView()
    let tableView = TableView()
    var list = [PhysicalAddressViewModel]()
    //用于延时500ms搜索地址
    var delaySearchTimer: Timer?
    
    let searchAddressBtn = OperationButton(R.string.localizable.search())

    override func setUpView() {
        self.backgroundColor = UIColor(hexStr: Constant.SystemBackColor)
        
        //searchTipLabel
        let installationTipLabel = ContentLabel()
        installationTipLabel.text = R.string.localizable.gwtnoswhnoOwnerName()
        installationTipLabel.numberOfLines = 0
        self.addSubview(installationTipLabel)
        installationTipLabel.snp.makeConstraints { make in
            make.top.equalTo(topBackView.snp.bottom).offset(Constant.AllOutMargin)
            make.left.equalTo(Constant.AllOutMargin)
            make.right.equalTo(-Constant.AllOutMargin)
            make.height.greaterThanOrEqualTo(0)
        }
        
        //installation textfield
        searchTextfield.placeholder = R.string.localizable.gwtnoswhnoOwnerName()
        searchTextfield.returnKeyType = .next
        searchTextfield.delegate = self
        self.addSubview(searchTextfield)
        searchTextfield.snp.makeConstraints { make in
            make.top.equalTo(installationTipLabel.snp_bottomMargin).offset((Constant.AllOutMargin))
            make.left.equalTo(Constant.AllOutMargin)
            make.right.equalTo(-Constant.AllOutMargin)
            make.height.equalTo(DIYTextField.height)
        }
        
        //searchTipLabel
        let addressTipLabel = ContentLabel()
        addressTipLabel.text = R.string.localizable.installationAddress()
        addressTipLabel.numberOfLines = 0
        self.addSubview(addressTipLabel)
        addressTipLabel.snp.makeConstraints { make in
            make.top.equalTo(searchTextfield.snp_bottomMargin).offset((Constant.AllOutMargin))
            make.left.equalTo(Constant.AllOutMargin)
            make.right.equalTo(-Constant.AllOutMargin)
            make.height.greaterThanOrEqualTo(0)
        }

        //search textfield
        addressTextfield.placeholder = R.string.localizable.searchForAnAddress()
        addressTextfield.returnKeyType = .done
        addressTextfield.delegate = self
        
        //编辑过程中进行查找
        self.addSubview(addressTextfield)
        addressTextfield.snp.makeConstraints { make in
            make.top.equalTo(addressTipLabel.snp_bottomMargin).offset((Constant.AllOutMargin))
            make.left.equalTo(Constant.AllOutMargin)
            make.right.equalTo(-Constant.AllOutMargin)
            make.height.equalTo(DIYTextField.height)
        }
        //searchTipLabel
        let searchTipLabel = ContentLabel(R.font.interRegular(size: 11),hexStr: "#292D3299")
        searchTipLabel.text = R.string.localizable.eGUnitOptional123SampleStreetSydneyNSW2000()
        searchTipLabel.numberOfLines = 0
        self.addSubview(searchTipLabel)
        searchTipLabel.snp.makeConstraints { make in
            make.top.equalTo(addressTextfield.snp_bottomMargin).offset((Constant.TopBottomMargin))
            make.left.right.equalTo(addressTextfield)
            make.height.greaterThanOrEqualTo(0)
        }
        
        // search btn
        searchAddressBtn.backgroundColor = UIColor(hexStr: "#70798A")
        self.addSubview(searchAddressBtn)
        searchAddressBtn.snp.makeConstraints { make in
            make.bottom.equalTo(OperationButton.bottomMargin)
            make.left.equalTo(Constant.AllOutMargin)
            make.right.equalTo(-Constant.AllOutMargin)
            make.height.equalTo(OperationButton.height)
        }
        searchAddressBtn.addTarget(self, action: #selector(addAddressBtnClick), for: UIControl.Event.touchUpInside)
        
        // address list
        tableView.layer.cornerRadius = Constant.StandardCornerRadius
        tableView.backgroundColor = UIColor(hexStr: "#9FACBE33")
        tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        tableView.showsVerticalScrollIndicator = false
        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableView.automaticDimension
        tableView.keyboardDismissMode = .onDrag
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.isHidden = true
        tableView.register(SearchAddressCell.self, forCellReuseIdentifier: SearchAddressCell.reuseCellIdentifier)
        self.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(searchTipLabel.snp_bottomMargin).offset((Constant.AllOutMargin))
            make.left.right.equalTo(addressTextfield)
            make.bottom.equalTo(searchAddressBtn.snp.top).offset(-Constant.AllOutMargin)
        }

//        viewTabBg.backgroundColor = UIColor.clear
//        viewTabBg.isHidden = true
//        self.addSubview(viewTabBg)
//        viewTabBg.snp.makeConstraints { make in
//            make.edges.equalToSuperview()
//        }
//        do {
//            let btnBg = BaseButton()
//            btnBg.backgroundColor = UIColor.clear
//            viewTabBg.addSubview(btnBg)
//            btnBg.snp.makeConstraints { make in
//                make.edges.equalToSuperview()
//            }
//            btnBg.addTarget(self, action: #selector(hideTableViewBtnClick), for: UIControl.Event.touchUpInside)
//            
//            // address list
//            tableView.layer.cornerRadius = Constant.StandardCornerRadius
//            tableView.backgroundColor = UIColor(hexStr: "#9FACBE33")
//            tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
//            tableView.showsVerticalScrollIndicator = false
//            tableView.estimatedRowHeight = 200
//            tableView.rowHeight = UITableView.automaticDimension
//            tableView.separatorStyle = .none
//            tableView.delegate = self
//            tableView.dataSource = self
//            tableView.register(SearchAddressCell.self, forCellReuseIdentifier: SearchAddressCell.reuseCellIdentifier)
//            viewTabBg.addSubview(tableView)
//            tableView.snp.makeConstraints { make in
//                make.top.equalTo(searchTipLabel.snp_bottomMargin).offset((Constant.AllOutMargin))
//                make.left.right.equalTo(addressTextfield)
//                make.bottom.equalTo(Constant.BottomMargin)
//            }
//        }
        
        initBiding()
    }
    
    //MARK: - 数据绑定
    func initBiding(){
        
        searchTextfield.rx.controlEvent(.editingChanged).subscribe{ [weak self] _ in
            guard let strongSelf = self else { return  }
            let jobStr = strongSelf.searchTextfield.text ?? "";
            let addressValue = strongSelf.addressTextfield.text ?? ""
            if(jobStr.count > 0 || addressValue.count > 0) {
                strongSelf.searchAddressBtn.enableBtn()
            } else {
                strongSelf.searchAddressBtn.disableBtn()
            }
        }.disposed(by: self.disposeBag)
        
        addressTextfield.rx.controlEvent(.editingChanged).subscribe{ [weak self] _ in
            guard let strongSelf = self else { return  }
            strongSelf.addressModel = nil
            let jobStr = strongSelf.searchTextfield.text ?? "";
            let addressValue = strongSelf.addressTextfield.text ?? ""
            if(jobStr.count > 0 || addressValue.count > 0) {
                strongSelf.searchAddressBtn.enableBtn()
            } else {
                strongSelf.searchAddressBtn.disableBtn()
            }
            DaisyNet.cancel(APIConfig.getRequestAPIForV2(APIConfig.GetAddressListAPI))
            strongSelf.delaySearchTimer?.invalidate()  // Cancel any previous timer
            // If the textField contains at least 3 characters…
            let currentText = (strongSelf.addressTextfield.text ?? "").trimmingCharacters(in: .whitespaces)
//            DebugLog(currentText)
            if currentText.count >= 4 {//超过四位才搜索
                 // …schedule a timer for 0.5 seconds
                strongSelf.delaySearchTimer = Timer.scheduledTimer(timeInterval: 0.5, target: strongSelf, selector: #selector(strongSelf.getAddressListBySearchValue), userInfo: nil, repeats: false)
            } else {
                //少于4位，显示空白
                strongSelf.list.removeAll()
                strongSelf.tableView.reloadData()
                strongSelf.tableView.isHidden = true
//                strongSelf.viewTabBg.isHidden = true
//                strongSelf.searchAddressBtn.isHidden = false
            }
        }.disposed(by: self.disposeBag)

//        addressTextfield.rx.controlEvent(.editingDidEndOnExit).subscribe { [weak self] _ in
//            guard let strongSelf = self else {return }
//            strongSelf.addressValue = ""
//            guard let searchText = strongSelf.addressTextfield.text , searchText.trimmingCharacters(in: .whitespaces).count >= 4 else {return}
//            strongSelf.getAddressListBySearchValue()
//        }.disposed(by: self.disposeBag)
        
    }

    
//    @objc private func hideTableViewBtnClick(){
//        self.viewTabBg.isHidden = true
//        self.searchAddressBtn.isHidden = false
//    }
    
    //MARK: - 根据search value获取address list
    @objc private func getAddressListBySearchValue(){
        let addressValue = (self.addressTextfield.text ?? "").trimmingCharacters(in: .whitespaces)
//        if(self.addressStr == addressValue) {
//            // 相同的数据
//            return
//        }
        self.addressStr = addressValue
        let vm = DictionaryService()
        vm.setBlockAfterNetwork { [weak self] (result, _) in
            guard let strongSelf = self else {return}
//            ModelViewUtil.shared.hideLoadingView()        
            strongSelf.list.removeAll()
            if let list = result as? Array<PhysicalAddressViewModel>{
                strongSelf.list = list
                strongSelf.tableView.reloadData()
            }
            //没有数据显示not data view，有数据隐藏not data view
            strongSelf.tableView.isHidden = false
//            strongSelf.viewTabBg.isHidden = false;
//            strongSelf.searchAddressBtn.isHidden = true
            strongSelf.tableView.showResultView(nodataFlag: false,tipMsg: R.string.localizable.noMatchedAddress())
            if(strongSelf.list.count > 0) {
                strongSelf.tableView.backgroundColor = UIColor(hexStr: "#9FACBE33")
            } else {
                strongSelf.tableView.backgroundColor = UIColor.clear
            }
        } errorBlock: { [weak self] (code, error) in
            guard let strongSelf = self else {return}
//            ModelViewUtil.shared.hideLoadingView()
            strongSelf.endEditing(true)
            strongSelf.list.removeAll()
            strongSelf.tableView.isHidden = false
//            strongSelf.viewTabBg.isHidden = false;
//            strongSelf.searchAddressBtn.isHidden = true
            strongSelf.tableView.reloadData()
            strongSelf.tableView.showRetryView()
            Tool().showAlertViewWithOneBtn(message: error)
        }
//        ModelViewUtil.shared.showLoadingView(parentView: self)
        vm.getAddressList(addressValue)
    }
    
    //MARK: - 点击搜索
    @objc func addAddressBtnClick() {
        self.endEditing(true)
        if let editingChangedClosure = self.editingChangedClosure {
            let jobStr = (self.searchTextfield.text ?? "").trimmingCharacters(in: .whitespaces)
            let address = self.addressStr
            editingChangedClosure(jobStr , address , self.addressModel)
        }
    }
    
}


extension JobsInputSearchView: UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.list.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: SearchAddressCell.reuseCellIdentifier) as? SearchAddressCell
        if cell == nil {
            cell = SearchAddressCell(style: .default, reuseIdentifier: SearchAddressCell.reuseCellIdentifier)
        }
        cell!.setData(self.list[indexPath.row].full_address)
        cell!.cellColor = tableView.backgroundColor
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.addressModel = self.list[indexPath.row]
        let addressValue = self.addressModel?.full_address ?? "";
        self.addressTextfield.text = addressValue
        self.addressStr = "";
        self.list.removeAll()
        self.tableView.isHidden = true
//        self.viewTabBg.isHidden = true;
//        self.searchAddressBtn.isHidden = false
        let jobStr = self.searchTextfield.text ?? "";
        if(jobStr.count > 0 || addressValue.count > 0) {
            self.searchAddressBtn.enableBtn()
        } else {
            self.searchAddressBtn.disableBtn()
        }
    }


    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.endEditing(true)
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        if(textField == self.searchTextfield) {
//            self.viewTabBg.isHidden = true
//            self.searchAddressBtn.isHidden = false
        }
        
        if(textField == self.addressTextfield) {
            if(self.addressModel == nil) {
                self.addressStr = (self.addressTextfield.text ?? "").trimmingCharacters(in: .whitespaces)
//                self.viewTabBg.isHidden = true
//                self.searchAddressBtn.isHidden = false
            }
        }
    }
}
